package com.example.jetpackcomposelazycolumn.ui.screens

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.VerticalAlignTop
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.navigate
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import com.example.jetpackcomposelazycolumn.ErrorItem
import com.example.jetpackcomposelazycolumn.ImagePagingViewModel
import com.example.jetpackcomposelazycolumn.LoadingItem
import com.example.jetpackcomposelazycolumn.LoadingView
import com.example.jetpackcomposelazycolumn.R
import com.example.jetpackcomposelazycolumn.ui.progress.DeterminateProgress
import com.google.accompanist.coil.CoilImage
import kotlinx.coroutines.launch

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun ImageList(navController: NavController) {
    Box {
        val viewModel: ImagePagingViewModel = viewModel()
        val lazyPagingItems = viewModel.post.collectAsLazyPagingItems()
        val listState = rememberLazyListState()
        val coroutineScope = rememberCoroutineScope()
        LazyColumn(state = listState) {
            val items = lazyPagingItems.snapshot().items
            println("item count :${items.size}")
            items(lazyPagingItems) { post ->
                Surface {
                    CoilImage(
                        data = post!!.preview,
                        contentScale = ContentScale.Crop,
                        contentDescription = post.preview,
                        modifier = Modifier
                            .clickable {
                                navController.currentBackStackEntry?.arguments?.putString(
                                    "imageUrl",
                                    post.preview
                                )
                                navController.currentBackStackEntry?.arguments?.putParcelable(
                                    "post",
                                    post
                                )
                                navController.navigate("detailScreen")
//                                navController.navigate("detailScreen/${post.preview}")
                            }
                            .fillMaxWidth()
                            .height(
                                (400 * post.height / post.width).dp
                            )
                            .border(width = 1.dp, color = Color.White),
                        loading = {
                            Image(
                                painter = painterResource(id = R.drawable.ic_photo),
                                contentScale = ContentScale.FillBounds,
                                contentDescription = null,
                                alpha = 0.45f
                            )
                        },
                        error = {
                            Image(
                                painter = painterResource(id = R.drawable.ic_broken_image),
                                contentScale = ContentScale.FillBounds,
                                contentDescription = null,
                                alpha = 0.45f
                            )
                        }
                    )
                }
            }
            // 加载 Paging 数据
            lazyPagingItems.apply {
                when {
                    loadState.refresh is LoadState.Loading -> {
                        item { LoadingView(modifier = Modifier.fillParentMaxSize()) }
                    }
                    loadState.append is LoadState.Loading -> {
                        item { LoadingItem() }
                    }
                    loadState.refresh is LoadState.Error -> {
                        val e = lazyPagingItems.loadState.refresh as LoadState.Error
                        item {
                            ErrorItem(
                                message = e.error.localizedMessage!!,
                                modifier = Modifier.fillParentMaxSize(),
                                onClickRetry = { retry() }
                            )
                        }
                    }
                    loadState.append is LoadState.Error -> {
                        val e = lazyPagingItems.loadState.append as LoadState.Error
                        item {
                            ErrorItem(
                                message = e.error.localizedMessage!!,
                                modifier = Modifier.fillParentMaxSize(),
                                onClickRetry = { retry() }
                            )
                        }
                    }
                }
            }
        }

        // 返回顶部
        val showButton = listState.firstVisibleItemScrollOffset > 0
        AnimatedVisibility(
            visible = showButton,
            enter = fadeIn(),
            exit = fadeOut(),
            modifier = Modifier
                .align(Alignment.BottomEnd)
                .padding(bottom = 20.dp, end = 20.dp)
        ) {
            FloatingActionButton(onClick = {
                coroutineScope.launch {
                    listState.animateScrollToItem(0)
                }
            }) {
                Icon(imageVector = Icons.Default.VerticalAlignTop, contentDescription = "")
            }
        }
    }
}